#!/bin/bash

set -e
shopt -s extglob

genpage() { # genpage <base dir> <source file>
	local basedir="$(realpath $1)"
	local sourcefile="$(realpath $2)"
	case "$sourcefile" in
		*.md)
			pagetitle="$(head -n1 "$sourcefile")"
			/usr/bin/pandoc -f markdown_mmd+backtick_code_blocks -t html5 "$sourcefile" > /tmp/page.htm
			;;
		*.rst)
			pagetitle="$(head -n1 "$sourcefile")"
			rst2html5 --template=rst-template.txt "$sourcefile" > /tmp/page.htm
			;;
		*)
			return
			;;
	esac

	cd wepage-tpl
	
	m4 -DBASEDIR="${basedir}" -DSOURCEFILE="${sourcefile}" << EOF
define(pageTitle, $pagetitle)dnl
include(\`page_tpl.m4')dnl
EOF

	cd ..
}

indexpage() { # indexpage <base> <relative path>
    basedir="$1"
    path="$2"
    echo '<h1 class="dir-list-head">' "${path}" '</h1><ul class="dir-list">'
    for fn in $(ls -F "$basedir/$path")
    do
	if test "x$fn" = 'xindex.htm'; then
	    continue
	fi
	case "$fn" in
	    *.htm)
		name="${fn%\.htm}"
		;;
	    *)
		name="${fn}"
		;;
	esac
	echo "<li><a href=\"${fn}\">${name}</a></li>"
    done
    echo '</ul>'
}

genindex() { # genindex <base> <relative path>
    local basedir="$(realpath $1)"
    local sourcefile="${basedir}/$2"
    indexpage "$1" "$2" > /tmp/page.htm

    cd wepage-tpl
    m4 -DBASEDIR="${basedir}" -DSOURCEFILE="${sourcefile}/index.htm" << EOF
define(pageTitle, $pagetitle)dnl
include(\`page_tpl.m4')dnl
EOF

    cd ..
}

basedir="${1%/}"
destdir="$(realpath $2)"

if test -e "$destdir"; then
	echo "${destdir} exists, please use another directory." >&2
	exit 1
fi

FILELIST=($(find ${basedir} -type f -and \( ! -path '*/.*' -and ! -path '*/_*' -and ! -path '*~' \)))
for f in "${FILELIST[@]}"
do
	filepath="${f#$basedir}" # remove prefix
	install -d "$destdir/$(dirname "$filepath")"
	case "$filepath" in
		*.rst)
			newname="${filepath%.rst}".htm
			;;
		*.md)
			newname="${filepath%.md}".htm
			;;
		*)
			cp "$f" "$destdir/$filepath"
			continue
			;;
	esac
	echo genpage "$basedir" "$f" >&2
	genpage "$basedir" "$f" > "$destdir/$newname"
done

DIRLIST=($(find "$destdir" -type d))
for d in "${DIRLIST[@]}"
do
    if [ ! -f "${d}/index.htm" ]; then
	filepath="${d#$destdir}" # remove the prefix
	filepath="${filepath#/}" # also remove the prefix /
	echo genindex "$destdir" "$filepath" >&2
	genindex "${destdir}" "${filepath}" > "${d}/index.htm"
    fi
done

cp -r pub "${destdir}/"
